package com.kehutong.material.service.impl;

import java.io.IOException;
import java.util.List;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.util.Objects;
import com.kehutong.material.entity.WelCome;
import com.kehutong.material.service.WelcomeService;

/**
 * 欢迎语
 *
 * @Author: liuzhen (liuxing521a@163.com)
 * @Date: 20/4/15 下午4:52
 */
@WebService("/crm/material/welcome")
public class WelcomeServiceImpl implements WelcomeService {
	
	@Inject
	private JdbcSession sqlSession;

	@ReqMapping("/getDefault")
	@Override
	public WelCome getDefault() {
		List<WelCome> welcomeList = sqlSession.findArray(WelCome.class)
    			.eq("defWelcome", true)
				.eq("deleted", false)
				.exe();
		if (Objects.isEmpty(welcomeList)) {
			return null;
		}
		
		return welcomeList.get(0);
	}
	
	@Override
	public Object setDefault(String id) {
		List<WelCome> welcomeList = sqlSession.findArray(WelCome.class)
    			.eq("defWelcome", true)
				.eq("deleted", false)
				.exe();
		
		welcomeList.forEach(item->item.setDefWelcome(false));
		sqlSession.updateById(welcomeList);
		
		WelCome welcome = Pool.get(WelCome.class, id);
		welcome.setDefWelcome(true);
		sqlSession.updateById(welcome);
		
		return Result.success();
	}

	@Override
	public Page<WelCome> list(JSONObject jsonObject) throws IOException {
		return sqlSession.findPage(WelCome.class)
    			.eq(jsonObject, "companyNo", "id")
    			.like(jsonObject, "name", "title", "content")
				.eq("deleted", false)
				.page(jsonObject)
				.exe();
	}

	@Override
	public WelCome get(String id) {
		return Pool.get(WelCome.class, id);
	}

	@Override
	public Object save(WelCome welcome, JSONObject jsonObject) throws IOException {
    	sqlSession.insert(welcome);

    	if (welcome.isDefWelcome()) {
			setDefault(welcome.getId());
		}

    	return Result.success();
	}

	@Override
	public Object update(WelCome welcome, JSONObject jsonObject) throws IOException {
    	sqlSession.updateById(welcome);

    	if (welcome.isDefWelcome()) {
			setDefault(welcome.getId());
		}
    	
    	return Result.success();
	}

	@Override
	public Object delete(String id) throws IOException {
		WelCome item = Pool.get(WelCome.class, id);
    	
    	if (item != null) {
    		item.setDeleted(true);
    		sqlSession.updateById(item);
    	}
    	return Result.success();
	}

}
